<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" v-show="showSearch" :inline="true" label-width="100px">
      <el-form-item label="所属租户组" prop="tenantGroupId">
        <el-select v-model="queryParams.tenantGroupId" filterable clearable placeholder="选择所属租户组" style="width: 200px">
          <el-option v-for="item in groupList" :key="item.tenantGroupName" :label="item.tenantGroupName"
            :value="item.tenantGroupId" />
        </el-select>
      </el-form-item>
      <el-form-item label="应用" prop="applicantId">
        <el-select v-model="queryParams.applicantId" filterable clearable placeholder="选择应用" style="width: 200px">
          <el-option v-for="item in appLicationList" :key="item.applicantName" :label="item.applicantName"
            :value="item.applicantId" />
        </el-select>
      </el-form-item>
      <el-form-item label="租户编码" prop="tenantCode">
        <el-input v-model="queryParams.tenantCode" placeholder="请输入租户编码" clearable style="width: 200px"
          @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="租户名称" prop="tenantName">
        <el-input v-model="queryParams.tenantName" placeholder="请输入租户名称" clearable style="width: 200px"
          @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button v-hasPermi="['gc:zh:xz']" type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <!-- 表格数据 -->
    <el-table v-loading="loading" :scrollbar-always-on="true" :data="tenantList">
      <el-table-column label="序号" type="index" width="100" />
      <el-table-column label="租户编号" prop="tenantCode" width="200" />
      <el-table-column label="uuid" prop="uuid" width="200">
        <template #default="scope">
          {{ scope.row.uuid || "--" }}
        </template>
      </el-table-column>
      <el-table-column label="应用类型" prop="applicantName" width="200" />
      <el-table-column label="租户名称" prop="tenantName" :show-overflow-tooltip="true" width="200" />
      <el-table-column label="所属组" prop="tenantGroupName" :show-overflow-tooltip="true" width="200" />
      <el-table-column label="租户简称" prop="tenantNameShort" :show-overflow-tooltip="true" width="200" />
      <el-table-column label="租户访问地址" prop="tenantUrl" :show-overflow-tooltip="true" width="300">
        <template #default="scope">
          <div class="f-fx">
            {{ scope.row.tenantUrl }}&nbsp;
            <el-link :underline="false" icon="DocumentCopy" @click="chsoeCopy(scope.row.tenantUrl)"
              style="float:right"></el-link>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="租户地址" prop="tenantAddress" :show-overflow-tooltip="true" width="200" />
      <el-table-column label="联系人" prop="tenantLinkName" :show-overflow-tooltip="true" width="200" />
      <el-table-column label="联系电话" prop="tenantLinkMobile" :show-overflow-tooltip="true" width="200" />
      <el-table-column label="状态" align="center" width="100">
        <template #default="scope">
          <el-switch v-model="scope.row.tenantAvl" @change="handleStatusChange(scope.row)" active-value="Y"
            inactive-value="N"></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="200">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="300" align="center" fixed="right" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-tooltip content="修改" placement="top">
            <el-button v-hasPermi="['gc:zh:xg']" link type="primary" icon="Edit"
              @click="handleUpdate(scope.row)"></el-button>
          </el-tooltip>
          <el-tooltip content="删除" placement="top">
            <el-button v-hasPermi="['gc:zh:sc']" link type="primary" icon="Delete" @click="handleDelete(scope.row)"></el-button>
          </el-tooltip>
          <el-tooltip content="重置超管密码" placement="top">
            <el-button v-hasPermi="['gc:zh:czmm']" link type="primary" icon="Refresh" @click="handleUpdatePassWord(scope.row)"></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改租户配置对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="roleRef" :model="form" :rules="rules" label-width="130px">
        <el-form-item label="所属租户组" prop="tenantGroupId">
          <el-select v-model="form.tenantGroupId" placeholder="选择所属租户组" style="width: 240px">
            <el-option v-for="item in groupList" :key="item.tenantGroupName" :label="item.tenantGroupName"
              :value="item.tenantGroupId" />
          </el-select>
        </el-form-item>
        <el-form-item label="应用" prop="applicantId">
          <el-select v-model="form.applicantId" placeholder="选择应用" style="width: 240px">
            <el-option v-for="item in appLicationList" :key="item.applicantName" :label="item.applicantName"
              :value="item.applicantId" />
          </el-select>
        </el-form-item>

        <el-form-item label="租户名称" prop="tenantName">
          <el-input v-model="form.tenantName" placeholder="请输入租户名称" />
        </el-form-item>
        <el-form-item label="租户编码" prop="tenantCode">
          <el-input v-model="form.tenantCode" placeholder="请输入租户编码" />
        </el-form-item>
        <el-form-item label="租户简称" prop="tenantNameShort">
          <el-input v-model="form.tenantNameShort" placeholder="请输入租户简称" />
        </el-form-item>
        <!--        <el-form-item label="租户访问地址" prop="tenantUrl">
          <el-input v-model="form.tenantUrl" placeholder="请输入租户访问地址" />
        </el-form-item> -->
        <!--        <el-form-item label="租户地址" prop="tenantAddress">
          <el-input v-model="form.tenantAddress" placeholder="请输入租户地址" />
        </el-form-item> -->

        <el-form-item label="状态" prop="tenantAvl">
          <el-radio-group v-model="form.tenantAvl">
            <el-radio v-for="dict in statusList" :key="dict.value" :value="dict.value">{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="租户Logo">
          <el-upload class="avatar-uploader" :show-file-list="false" :before-upload="beforeAvatarUpload"
            :http-request="uploadImageFile">
            <el-image v-if="form.tenantLogo" style="width: 100px; height: 100px" :src="form.tenantLogo" fit="fill" />
            <div v-else>
              <el-button type="primary">上传图片</el-button>
              <p style="display: block;color: #666;">上传jpeg/png格式，文件大小不能超过2M</p>
            </div>
          </el-upload>
        </el-form-item>
        <!--        <el-form-item label="超管密码" prop="adminPassword">
          <el-input v-model="form.adminPassword" type="password" show-password placeholder="请输入超管密码" />
        </el-form-item> -->
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="tenantIndex">
  import {
    addtenant,
    deltenant,
    gettenant,
    listtenant,
    updatetenant,
    changeAvl,
    editPassword
  } from "@/api/system/tenantindex";
  import { ElMessage, ElMessageBox } from 'element-plus'
  import {
    listgroup
  } from "@/api/system/tenantgroup";
  import {
    listapplicant,
  } from "@/api/system/applicant";
  import ImageUpload from "@/components/ImageUpload"
  const router = useRouter();
  const { proxy } = getCurrentInstance();
  const tenantList = ref([]);
  const groupList = ref([]);
  const appLicationList = ref([]);
  const open = ref(false);
  const loading = ref(true);
  const showSearch = ref(true);
  const ids = ref([]);
  const single = ref(true);
  const roleRef = ref()
  const multiple = ref(true);
  const total = ref(0);
  const title = ref("");
  const dateRange = ref([]);
  const deptOptions = ref([]);
  const openDataScope = ref(false);
  const menuRef = ref(null);
  const deptRef = ref(null);
  const statusList = ref([{
    label: '启用',
    value: 'Y'
  }, {
    label: '禁用',
    value: 'N'
  }])
  /** 数据范围选项*/
  const dataScopeOptions = ref([
    { value: "1", label: "全部数据权限" },
    { value: "2", label: "自定数据权限" },
    { value: "3", label: "本部门数据权限" },
    { value: "4", label: "本部门及以下数据权限" },
    { value: "5", label: "仅本人数据权限" }
  ]);

  const data = reactive({
    form: {},
    queryParams: {
      pageNum: 1,
      pageSize: 10,
    },
    rules: {
      applicantId: [{ required: true, message: "应用不能为空", trigger: "blur" }],
      tenantGroupId: [{ required: true, message: "所属租户组不能为空", trigger: "blur" }],
      tenantCode: [{ required: true, message: "租户编码不能为空", trigger: "blur" }, { pattern: /^[a-z0-9]+$/, message: '租户编码可以为小写字母和数字的组合', trigger: 'blur' }, {
        min: 3,
        max: 10,
        message: '租户编码长度在 3 到 10 个字符',
        trigger: 'blur'
      }],
      tenantName: [{ required: true, message: "租户名称不能为空", trigger: "blur" }],
      tenantNameShort: [{ required: true, message: "租户简称不能为空", trigger: "blur" }],
      tenantUrl: [{ required: true, message: "租户访问地址不能为空", trigger: "blur" }],
      tenantAddress: [{ required: true, message: "租户地址不能为空", trigger: "blur" }],
      tenantAvl: [{ required: true, message: "状态不能为空", trigger: "blur" }],
    },
  });

  const disabledDate = (time) => {
    return time.getTime() < Date.now() - 8.64e7; // 8.64e7 毫秒数代表一天
  };
  const { queryParams, form, rules } = toRefs(data);
  /** 租户状态修改 */
  function handleStatusChange(row) {
    let text = row.tenantAvl === "Y" ? "启用" : "禁用";
    proxy.$modal.confirm('确认要"' + text + '""' + row.tenantLinkName + '"租户吗?').then(function() {
      return changeAvl({ tenantId: row.tenantId, tenantAvl: row.tenantAvl });
    }).then((res) => {
      proxy.$modal.msgSuccess(text + "成功");
    }).catch(function() {
      row.tenantAvl = row.tenantAvl === "Y" ? "N" : "Y";
    });
  }
  /**
   * 上传封面图片
   */
  function uploadImageFile(options) {
    let that = this;
    let file = options.file;
    let model = URL.createObjectURL(file);
    var reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onloadend = function() {
      // 将文件（file）转换成base64字符串
      form.value.tenantLogo = reader.result;
    }
  };
  /**
   * 上传封面图片前检查
   */
  function beforeAvatarUpload(rawFile) {
    if (rawFile.type != "image/jpeg" && rawFile.type != "image/png") {
      proxy.$modal.msgWarning("请上传JPEG或PNG格式的图片文件!");
      return false;
    } else if (rawFile.size / 1024 / 1024 > 2) {
      proxy.$modal.msgWarning("封面图片的大小请小于2MB!");
      return false;
    }
    return true;
  };
  /** 查询租户列表 */
  function getList() {
    loading.value = true;
    listtenant(proxy.addDateRange(queryParams.value, dateRange.value)).then(response => {
      tenantList.value = response.rows
      total.value = response.total;
      loading.value = false;
    });
  }
  /** 查询租户组列表 */
  function getGroup() {
    listgroup({ pageNum: 1, pageSize: 10000 }).then(response => {
      groupList.value = response.rows
    });
  }
  /** 查询应用列表 */
  function getAppLication() {
    listapplicant({ pageNum: 1, pageSize: 10000 }).then(response => {
      appLicationList.value = response.rows
    });
  }
  /** 搜索按钮操作 */
  function handleQuery() {
    queryParams.value.pageNum = 1;
    getList();
  }

  /** 重置按钮操作 */
  function resetQuery() {
    dateRange.value = [];
    proxy.resetForm("queryRef");
    handleQuery();
  }

  /** 删除按钮操作 */
  function handleDelete(row) {
    const tenantIds = row.tenantId || ids.value;
    proxy.$modal.confirm('是否确认删除租户编号为"' + row.tenantCode + '"的数据项?').then(function() {
      return deltenant(tenantIds);
    }).then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    }).catch(() => {});
  }
  /** 删除按钮操作 */
  function handleUpdatePassWord(row) {
    const tenantIds = row.tenantId || ids.value;
    proxy.$modal.confirm('是否确认重置当前管理员密码?').then(function() {
      return editPassword({ tenantId: tenantIds });
    }).then((res) => {
      getList();
      proxy.$modal.msgSuccess(res.msg);
    }).catch(() => {});
  }
  /** 导出按钮操作 */
  function handleExport() {
    proxy.download("system/role/export", {
      ...queryParams.value,
    }, `role_${new Date().getTime()}.xlsx`);
  }

  /** 多选框选中数据 */
  function handleSelectionChange(selection) {
    ids.value = selection.map(item => item.tenantId);
    single.value = selection.length != 1;
    multiple.value = !selection.length;
  }

  /** 租户状态修改 */
  function handletenantAvlChange(row) {
    let text = row.tenantAvl === "0" ? "启用" : "停用";
    proxy.$modal.confirm('确认要"' + text + '""' + row.tenantName + '"租户吗?').then(function() {
      return changeRoletenantAvl(row.tenantId, row.tenantAvl);
    }).then(() => {
      proxy.$modal.msgSuccess(text + "成功");
    }).catch(function() {
      row.tenantAvl = row.tenantAvl === "0" ? "1" : "0";
    });
  }

  /** 更多操作 */
  function handleCommand(command, row) {
    switch (command) {
      case "handleDataScope":
        handleDataScope(row);
        break;
      case "handleAuthUser":
        handleAuthUser(row);
        break;
      default:
        break;
    }
  }

/** 复制代码成功 */
function chsoeCopy(text) {
  const save = function (e) {
    e.clipboardData.setData("text/plain", text);
    e.preventDefault();                     // 阻止默认行为
  };
  document.addEventListener("copy", save);  // 添加一个copy事件
  document.execCommand("copy");
  proxy.$modal.msgSuccess("复制成功");
}


  /** 所有部门节点数据 */
  function getDeptAllCheckedKeys() {
    // 目前被选中的部门节点
    let checkedKeys = deptRef.value.getCheckedKeys();
    // 半选中的部门节点
    let halfCheckedKeys = deptRef.value.getHalfCheckedKeys();
    checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
    return checkedKeys;
  }

  /** 重置新增的表单以及其他数据  */
  function reset() {
    form.value = {
      tenantGroupId: '',
      applicantId: undefined,
      tenantName: undefined,
      tenantNameShort: '',
      tenantUrl: '',
      tenantAddress: '',
      tenantLogo: '',
      tenantAvl: 'Y',
      adminPassword: ''
    };
  }

  /** 添加租户 */
  function handleAdd() {
    reset();
    open.value = true;
    rules.value['adminPassword'] = [{ required: true, message: "超过密码不能为空", trigger: "blur" }];
    title.value = "添加租户";
    setTimeout(() => {
      roleRef.value.resetFields()
    }, 100)
  }

  /** 修改租户 */
  async function handleUpdate(row) {
    reset();
    rules.value['adminPassword'] = [{ required: false, message: "超过密码不能为空", trigger: "blur" }];
    const tenantId = row.tenantId || ids.value;
    gettenant(tenantId).then(response => {
      open.value = true;
      setTimeout(() => {
        roleRef.value.resetFields()
        form.value = response.data;
      }, 100)
      title.value = "修改租户";

    });
  }

  /** 根据租户ID查询菜单树结构 */
  function gettenantMenuTreeselect(tenantId) {
    return roleMenuTreeselect(tenantId).then(response => {
      menuOptions.value = response.menus;
      return response;
    });
  }

  /** 根据租户ID查询部门树结构 */
  function getDeptTree(tenantId) {
    return deptTreeSelect(tenantId).then(response => {
      deptOptions.value = response.depts;
      return response;
    });
  }

  /** 树权限（展开/折叠）*/
  function handleCheckedTreeExpand(value, type) {
    if (type == "menu") {
      let treeList = menuOptions.value;
      for (let i = 0; i < treeList.length; i++) {
        menuRef.value.store.nodesMap[treeList[i].id].expanded = value;
      }
    } else if (type == "dept") {
      let treeList = deptOptions.value;
      for (let i = 0; i < treeList.length; i++) {
        deptRef.value.store.nodesMap[treeList[i].id].expanded = value;
      }
    }
  }

  /** 树权限（全选/全不选） */
  function handleCheckedTreeNodeAll(value, type) {
    if (type == "menu") {
      menuRef.value.setCheckedNodes(value ? menuOptions.value : []);
    } else if (type == "dept") {
      deptRef.value.setCheckedNodes(value ? deptOptions.value : []);
    }
  }

  /** 树权限（父子联动） */
  function handleCheckedTreeConnect(value, type) {
    if (type == "menu") {
      form.value.menuCheckStrictly = value ? true : false;
    } else if (type == "dept") {
      form.value.deptCheckStrictly = value ? true : false;
    }
  }

  /** 所有菜单节点数据 */
  function getMenuAllCheckedKeys() {
    // 目前被选中的菜单节点
    let checkedKeys = menuRef.value.getCheckedKeys();
    // 半选中的菜单节点
    let halfCheckedKeys = menuRef.value.getHalfCheckedKeys();
    checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
    return checkedKeys;
  }

  /** 提交按钮 */
  function submitForm() {
    proxy.$refs["roleRef"].validate(valid => {
      if (valid) {
        if (form.value.tenantId != undefined) {
          updatetenant(form.value).then(response => {
            proxy.$modal.msgSuccess("修改成功");
            open.value = false;
            getList();
          });
        } else {
          addtenant(form.value).then(response => {
            proxy.$modal.msgSuccess("新增成功");
            open.value = false;
            getList();
          });
        }
      }
    });
  }

  /** 取消按钮 */
  function cancel() {
    open.value = false;
    reset();
  }

  /** 选择租户权限范围触发 */
  function dataScopeSelectChange(value) {
    if (value !== "2") {
      deptRef.value.setCheckedKeys([]);
    }
  }

  /** 分配数据权限操作 */
  function handleDataScope(row) {
    reset();
    const deptTreeSelect = getDeptTree(row.tenantId);
    gettenant(row.tenantId).then(response => {
      form.value = response.data;
      openDataScope.value = true;
      nextTick(() => {
        deptTreeSelect.then(res => {
          nextTick(() => {
            if (deptRef.value) {
              deptRef.value.setCheckedKeys(res.checkedKeys);
            }
          });
        });
      });
      title.value = "分配数据权限";
    });
  }

  /** 提交按钮（数据权限） */
  function submitDataScope() {
    if (form.value.tenantId != undefined) {
      form.value.deptIds = getDeptAllCheckedKeys();
      dataScope(form.value).then(response => {
        proxy.$modal.msgSuccess("修改成功");
        openDataScope.value = false;
        getList();
      });
    }
  }

  /** 取消按钮（数据权限）*/
  function cancelDataScope() {
    openDataScope.value = false;
    reset();
  }
  getList();
  getGroup();
  getAppLication();
</script>